﻿//  Copyright (c) 2010 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using DNA.Mvc.jQuery;

namespace DNA.Mvc
{
    /// <summary>
    /// Defines the jQuery pluginable component base class.This class could be auto generate the jQuery scripts.  
    /// </summary>
    /// <typeparam name="TOptions"></typeparam>
    /// <typeparam name="TComponent"></typeparam>
    /// <typeparam name="TBuilder"></typeparam>
    public abstract class jQueryComponentBuilder<TOptions, TComponent, TBuilder> : ViewComponentBuilder<TComponent, TBuilder>
        where TComponent : ViewComponent
        where TBuilder : ViewComponentBuilder<TComponent, TBuilder>
    {
        protected TOptions options;

        /// <summary>
        /// Gets the jQuery plugin name
        /// </summary>
        protected abstract string jQueryPluginName { get; }

        /// <summary>
        /// Gets the jQuery selector by using current component id string. e.g: $("#component1")
        /// </summary>
        protected string jQuerySelector { get { return "$(\"#"+Component.Id+"\")"; } }

        public jQueryComponentBuilder(TComponent component, ViewContext context, IViewDataContainer container) : base(component, context, container) { }

       // public jQueryComponentBuilder(TComponent containerComponent, ViewContext viewContext, IViewDataContainer viewContainer) : base(containerComponent, viewContext, viewContainer) { }

        /// <summary>
        /// Set the Option settings.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public TBuilder Options(Action<TOptions> value)
        {
            if (options == null)
                options = Activator.CreateInstance<TOptions>();
            value.Invoke(options);
            return this as TBuilder;
        }

        public override void Render()
        {
            if (string.IsNullOrEmpty(jQueryPluginName))
                throw new ArgumentNullException("jQueryPluginName");
            base.Render();
            Helper.jQuery(Component.Id, jQueryPluginName, options);
        }

        public override MvcHtmlString GetHtml()
        {
            if (string.IsNullOrEmpty(jQueryPluginName))
                throw new ArgumentNullException("jQueryPluginName");
            Helper.jQuery(Component.Id, jQueryPluginName, options);
            return base.GetHtml();
        }
    }
}